<template>
  <div ref="chart" style="height: 400px;"></div>
</template>

<script>
import * as echarts from 'echarts'
import { getAgeData } from '@/api/analysis'

export default {
  name: 'AgeChart',
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.loadData()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',
          data: ['0-18岁', '19-25岁', '26-35岁', '36-45岁', '46岁以上']
        }
      })
    },
    async loadData() {
      try {
        const res = await getAgeData()
        const ageGroups = res.data.ageGroups
        const option = {
          series: [{
            name: '人数',
            type: 'bar',
            data: [
              ageGroups['0-18'],
              ageGroups['19-25'],
              ageGroups['26-35'],
              ageGroups['36-45'],
              ageGroups['46+']
            ],
            itemStyle: {
              color: function(params) {
                const colorList = ['#c23531','#2f4554','#61a0a8','#d48265','#91c7ae']
                return colorList[params.dataIndex]
              }
            }
          }],
          title: {
            text: `平均年龄：${res.data.averageAge.toFixed(1)}岁`,
            right: '5%',
            top: '5%'
          }
        }
        this.chart.setOption(option)
        window.addEventListener('resize', this.resizeHandler)
      } catch (error) {
        console.error('加载年龄数据失败:', error)
      }
    },
    resizeHandler() {
      this.chart.resize()
    }
  }
}
</script>
